﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;

namespace ChatForum.WCF
{
	public class InstanceProvider<TService> : IInstanceProvider, IServiceBehavior
	{
        private object serviceInstance;
        public InstanceProvider(TService serviceInstance)
		{
            this.serviceInstance = serviceInstance;
		}

		#region IInstanceProvider Members
		public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
		{
            return serviceInstance;
		}
		public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
		{
			return GetInstance(instanceContext, null);
		}
		public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance) { }
		#endregion

		#region IServiceBehavior Members
		public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { }
		public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
		{
			foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
			{
				ChannelDispatcher cd = cdb as ChannelDispatcher;
				if (cd != null)
				{
					foreach (EndpointDispatcher ed in cd.Endpoints)
					{
						ed.DispatchRuntime.InstanceProvider = this;
					}
				}
			}
		}
		public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { }
		#endregion
	}
}
